//
//  MSMemberServeViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/18.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSMemberServeViewController.h"
#import "MSMemberServeTableVC.h"
#import "MWProgressView.h"
#import "MSMemberTableFooterView.h"
#import "MSUploadCardViewController.h"

#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

@interface MSMemberServeViewController ()
@property (nonatomic, strong) MSMemberServeTableVC      *tableVC;
@property (nonatomic, strong) UIView                    *headerView;
@property (nonatomic, strong) UILabel                   *titleLabel;
@property (nonatomic, strong) GXButton                  *riseBtn;
@property (nonatomic, strong) MWProgressView            *progressView;
@property (nonatomic, strong) MSMemberServeModel        *serveModel;
@property (nonatomic, strong) MSMemberTableFooterView   *tableFooterView;
@end

@implementation MSMemberServeViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    leftBarBtn.hidden = NO;
    titleLable.text = @"会员服务";
}

- (void)initUI{
    self.tableVC = [[MSMemberServeTableVC alloc] initWithStyle:UITableViewStyleGrouped];
    self.tableVC.view.frame = self.contentView.bounds;
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
//    [self layoutHeaderView];
}

- (void)layoutHeaderView{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-24, 150)];
    _headerView.backgroundColor = [UIColor whiteColor];
    
    self.titleLabel = [self creatLabel:CGRectMake(12, 20, SCREEN_WIDTH-24, 20)];
    
    self.progressView = [[MWProgressView alloc] initWithFrame:CGRectMake(0, self.titleLabel.bottom+10, SCREEN_WIDTH, 50)];
    self.progressView.bgColor = kNormalGray;
    self.progressView.startColor = UIColorFromRGB(0xf1cc46);
    self.progressView.endColor = UIColorFromRGB(0xe8ab57);
    self.progressView.titleArray = @[@"临时会员",@"普通会员",@"高级会员",];
    self.progressView.selectedIndex = self.memberType;
    [_headerView addSubview:self.progressView];
    
    UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(12, self.progressView.bottom+5, SCREEN_WIDTH-24, 0.6)];
    horizonLineView.backgroundColor = kNormalGray;
    [_headerView addSubview:horizonLineView];
    
    UILabel *riseLabel = [self creatLabel:CGRectMake(12, horizonLineView.bottom+10, SCREEN_WIDTH-24, 20)];
    
    UIView *horizonLineView2 =[[UIView alloc] initWithFrame:CGRectMake(0, riseLabel.bottom+10, SCREEN_WIDTH, 0.6)];
    horizonLineView2.backgroundColor = kNormalGray;
    [_headerView addSubview:horizonLineView2];
    
    NSString *titleStr = @"";
    NSString *riseStr = @"";
    if (self.memberType == MemberType_temp) {
        titleStr = @"临时会员";
        riseStr = @" 升级为普通会员可以：";
        riseLabel.textColor = kLightBlackColor;
        
        UILabel *showLabel = [self creatLabel:CGRectMake(40, riseLabel.bottom+8, SCREEN_WIDTH-40, 60)];
        showLabel.numberOfLines = 0;
        NSString *showStr = @"1.享受所有基本功能\n2.发展成为高级会员享受更多特权";
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 8;
        
        NSMutableAttributedString *showAttStr = [[NSMutableAttributedString alloc] initWithString:showStr  attributes:@{NSParagraphStyleAttributeName:paragraphStyle}];
        
        showLabel.attributedText = showAttStr;
        
        _headerView.height = 210;
        
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        footerView.backgroundColor = kDefaultViewBackgroundColor;
        self.tableVC.tableView.tableFooterView = footerView;
        
        self.riseBtn = [[GXButton alloc] initWithFrame:CGRectMake(12, 25, SCREEN_WIDTH-24, 45)];
        self.riseBtn.titleLabel.font = HeitiFont(16);
        [self.riseBtn setTitle:@"上传名片并升级" forState:UIControlStateNormal];
        [self.riseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.riseBtn.backgroundColor = kBlueColor;
        self.riseBtn.layer.cornerRadius = 2;
        [self.riseBtn addTarget:self action:@selector(riseClick) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:self.riseBtn];
    }
    if (self.memberType == MemberType_common) {
        titleStr = @"普通会员";
        riseStr = @" 升级为高级会员可以使用系统所有功能";
    }
    if (self.memberType == MemberType_advanced) {
        titleStr = @"高级会员";
        
        riseStr = [NSString stringWithFormat:@" 会员有效期还剩%@天哦",self.serveModel.day];
    }

    NSMutableAttributedString *titleAttStr = [[NSMutableAttributedString alloc] initWithString:@"当前级别："  attributes:@{NSForegroundColorAttributeName:kDarkGrayColor}];
    NSAttributedString *levelStr = [[NSAttributedString alloc] initWithString:titleStr];
    [titleAttStr appendAttributedString:levelStr];
    self.titleLabel.attributedText = titleAttStr;
    
    NSMutableAttributedString *riseAttstr = [[NSMutableAttributedString alloc] initWithString:riseStr attributes:@{NSForegroundColorAttributeName:kLightBlackColor}];
    
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    textAttachment.bounds = CGRectMake(0, -3, 23, 19);
    textAttachment.image = [UIImage imageNamed:@"vstar"];
    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [riseAttstr insertAttributedString:attachmentString atIndex:0];
    
    riseLabel.attributedText = riseAttstr;
    
    horizonLineView2.top = _headerView.height-0.6;
    self.tableVC.tableView.tableHeaderView = _headerView;
    
    if (self.memberType != MemberType_temp){
        self.tableFooterView = [[MSMemberTableFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 220)];
        self.tableFooterView.delegate = (id)self;
//        self.tableFooterView.backgroundColor = [UIColor whiteColor];
        self.tableVC.tableView.tableFooterView = self.tableFooterView;
    }
}

//创建label
- (UILabel*)creatLabel:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = HeitiFont(15);
    label.textColor = [UIColor blackColor];
    [_headerView addSubview:label];
    return label;
}

- (void)testDataFunc{
    [netEngine requestMemberServeWithTarget:self.VctrID hudView:self.contentView];
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"MemberServe"]!=nil){
            self.serveModel = responseDic[@"MemberServe"];
            if ([self.serveModel.level isEqualToString:@"3"]) {
                self.memberType = MemberType_advanced;
            }
            else if ([self.serveModel.level isEqualToString:@"2"]) {
                self.memberType = MemberType_common;
            }
            else if ([self.serveModel.level isEqualToString:@"1"]) {
                self.memberType = MemberType_temp;
            }
            [self layoutHeaderView];
            [self setPurchase];
            self.tableVC.serveModel = self.serveModel;
            [self.tableVC.tableView reloadData];
        }
        if (responseDic[@"MemberPurchase"]!=nil){
            [HDUtil showMessage:@"购买成功"];
            [rootNavigation popViewControllerAnimated:YES];
        }
    }
}

- (void)setPurchase{
    if (self.memberType != MemberType_temp) {
        MSCommonModel *model = [[MSCommonModel alloc] init];
        model.title = @"1";
        model.subTitle = @"10";
        model.thirdTitle = self.memberType == MemberType_common?@"升级":@"续费";//余额
        
        MSCommonModel *model2 = [[MSCommonModel alloc] init];
        model2.title = @"7";
        model2.subTitle = @"30";
        model2.thirdTitle = model.thirdTitle;
        
        MSCommonModel *model3 = [[MSCommonModel alloc] init];
        model3.title = @"30";
        model3.subTitle = @"100";
        model3.thirdTitle = model.thirdTitle;
        
        self.tableVC.dataArray = [@[model,model2,model3] mutableCopy];
    }
}

//临时会员上传名片并升级
- (void)riseClick{
    MSUploadCardViewController *vc = [[MSUploadCardViewController alloc] init];
    [rootNavigation pushViewController:vc animated:YES];
}

#pragma mark - MSMemberServeCellDelegate
- (void)selectBtnWithIndex:(NSInteger)btnIndex{
    MSCommonModel *model = self.tableVC.dataArray[btnIndex];
    if ([self.serveModel.wallet integerValue] < [model.subTitle integerValue]) {
        [HDUtil showMessage:@"余额不足"];
        return;
    }
    NSString *showStr = [NSString stringWithFormat:@"是否支付%@江湖币兑换%@天会员",model.subTitle,model.title];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:showStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alertView.tag = [model.title intValue];
    [alertView show];
}

#pragma mark - MSMemberTableFooterViewDelegate
- (void)tableFooterViewSelectBtnWithIndex:(NSInteger)btnIndex{
    if (btnIndex == 10) {//发布交易
        MSReleaseTradeViewController *vc = [[MSReleaseTradeViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
        return;
    }
    if (btnIndex == 11) {//邀请通讯录好友
        MSInviteFriendsViewController *vc = [[MSInviteFriendsViewController alloc] init];
        [rootNavigation pushViewController:vc animated:YES];
        return;
    }
    return;
    __weak typeof(self)weakSelf = self;
    //分享
    CGFloat imageWidth = 200;
    UIImage *newImage = [self imageCompressForWidth:[UIImage imageNamed:@""] targetWidth:imageWidth];
    NSData *imageData = UIImagePNGRepresentation(newImage);
    //    NSLog(@"原分享图片->%lu KB",imageData.length/1024);
    while (imageData.length/1024 >= 31) {
        imageWidth -= 10;
        newImage = [self imageCompressForWidth:[UIImage imageNamed:@""] targetWidth:imageWidth];
        imageData = UIImagePNGRepresentation(newImage);
    }
    if (btnIndex == 0) {//新浪
        //将在新浪微博注册的应用appkey、redirectURL替换下面参数，并在info.plist的URL Scheme中相应添加wb+appkey，如"wb3921700954"，详情请参考官方文档。
        //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。若在新浪后台设置我们的回调地址，“http://sns.whalecloud.com/sina2/callback”，这里可以传nil
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:sinaAppKey appSecret:sinaAppSecret redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"测试分享" descr:[NSString stringWithFormat:@"%@",@"描述副标题"] thumImage:imageData];
        //设置网页地址
        shareObject.webpageUrl = @"";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_Sina messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"weibo分享成功！");
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }
    if (btnIndex == 1) {//微信
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:wechatAppID appSecret:wechatAppSecret redirectURL:nil];
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"测试分享" descr:[NSString stringWithFormat:@"%@\n%@",@"描述副标题",@"描述副标题"] thumImage:imageData];
        //设置网页地址
        shareObject.webpageUrl = @"";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"wechat分享成功！");
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }
    if (btnIndex == 2) {//微信圈
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:wechatAppID  appSecret:wechatAppSecret redirectURL:nil];
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@ %@",@"测试分享",@"测试分享"] descr:[NSString stringWithFormat:@"%@ %@",@"测试分享",@"测试分享"] thumImage:imageData];
        //设置网页地址
        shareObject.webpageUrl = @"";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"wechat分享成功！");
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }
    if (btnIndex == 3) {//QQ
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey appSecret:QQAppSecret redirectURL:nil];
        //设置支持没有客户端情况下使用SSO授权
        [[UMSocialQQHandler defaultManager] setSupportWebView:YES];
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@",@"测试分享"] descr:[NSString stringWithFormat:@"%@",@"测试分享"] thumImage:imageData];
        //设置网页地址
        shareObject.webpageUrl = @"";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"QQ分享成功！");
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }
    if (btnIndex == 4) {//QQ空间
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:QQAppKey appSecret:QQAppSecret redirectURL:nil];
        //设置支持没有客户端情况下使用SSO授权
        [[UMSocialQQHandler defaultManager] setSupportWebView:YES];
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@",@"测试分享"] descr:[NSString stringWithFormat:@"%@",@"测试分享"] thumImage:imageData];
        //设置网页地址
        shareObject.webpageUrl = @"";
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    NSLog(@"QQ空间分享成功！");
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
        }];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [netEngine requestMemberPurchaseWithTarget:self.VctrID hudView:self.contentView day:[NSString stringWithFormat:@"%ld",alertView.tag]];
    }
    //    [netEngine requestMemberPurchaseWithTarget:self.VctrID hudView:self.contentView day:[NSString stringWithFormat:@"7"]];

}

//压缩图片
-(UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth {
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end
